package cn.wenhe9.novel.manager;

import cn.wenhe9.novel.constant.CacheConsts;
import cn.wenhe9.novel.constant.DatabaseConsts;
import cn.wenhe9.novel.domain.dto.NewsInfoDto;
import cn.wenhe9.novel.domain.entity.news.NewsInfo;
import cn.wenhe9.novel.mapper.NewsInfoMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 新闻 缓存管理类
 *
 * @author DuJinliang
 * 2022/5/18
 */
@Component
public class NewsCacheManager {

    @Resource
    private NewsInfoMapper newsInfoMapper;

    /**
     * 最新新闻列表查询，并放入缓存中
     */
    @Cacheable(cacheManager = CacheConsts.REDIS_CACHE_MANAGER
            , value = CacheConsts.LATEST_NEWS_CACHE_NAME)
    public List<NewsInfoDto> listLatestNews() {
        // 从新闻信息表中查询出最新发布的两条新闻
        QueryWrapper<NewsInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(DatabaseConsts.CommonColumnEnum.CREATE_TIME.getName())
                .last(DatabaseConsts.SqlEnum.LIMIT_2.getSql());
        return newsInfoMapper.selectList(queryWrapper).stream().map(v -> NewsInfoDto.builder()
                .id(v.getId())
                .categoryId(v.getCategoryId())
                .categoryName(v.getCategoryName())
                .title(v.getTitle())
                .sourceName(v.getSourceName())
                .updateTime(v.getUpdateTime())
                .build()).collect(Collectors.toList());
    }

}
